package com.icepeach.icepeachhomeback.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.icepeach.icepeachhomeback.entity.MyFile;
import com.icepeach.icepeachhomeback.service.MyFileService;
import com.icepeach.icepeachhomeback.util.ApiResult;
//import com.sun.deploy.net.URLEncoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * 文件上传相关接口
 */

@Controller
@RequestMapping("/file")
public class FileController {
    @Value("${files.upload.path}")
    private String filesUploadPath;
    @Resource
    MyFileService myFileService;

    //！！！！！！！这里猜了大坑！因为没有加ResponseBody，所以一致返回401，烦死了！！
    @PostMapping("/upload")
    @ResponseBody
    public ApiResult upload(@RequestParam  MultipartFile file) throws IOException {
        String originalFileName = file.getOriginalFilename();
        String type = FileUtil.extName(originalFileName);
        long size = file.getSize();
        //---------存储到磁盘
        File uploadParentFile = new File(filesUploadPath);
        //判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }
        //定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUuid = uuid + StrUtil.DOT + type;
        //实际file路径
        File uploadFile = new File(filesUploadPath + fileUuid);
        //把获取到的文件存储到磁盘目录
        file.transferTo(uploadFile);

        //存储到数据库
        String url = "http://localhost:8082/file/" + fileUuid;
        MyFile myFile = new MyFile();
        myFile.setName(originalFileName);
        myFile.setSize(size/1024);
        myFile.setType(type);
        myFile.setUrl(url);
        myFileService.save(myFile);

        return ApiResult.success("创建成功", url);
    }

    /**
     * 文件下载接口 http://localhost:8082/file/{fileUUID}
     * @param fileUUID
     * @param httpServletResponse
     * @throws IOException
     */
    @GetMapping("/{fileUUID}")
    @ResponseBody
    public void download(@PathVariable String fileUUID, HttpServletResponse httpServletResponse) throws IOException {
        //根据文件的唯一标识码获取文件
        File uploadFile = new File(filesUploadPath + fileUUID);
        ServletOutputStream os = httpServletResponse.getOutputStream();
        httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        httpServletResponse.setContentType("application/octet-stream");
//读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
}
